<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button onclick="store.dispatch({type:'COUNT_DECREMENT',num:1})">-</button>
  <h1 id="count"></h1>
  <button onclick="store.dispatch({type:'COUNT_INCREMENT',num:1})">+</button>

  <script>
    //集中管理state,和dispatch,action
    const createStore = (reducer) => {
      let state = null;
      const getState = () => state;
      //定义一个监听器队列，管理所有订阅的方法
      const listeners = [];
      const subscribe = (listener) => listeners.push(listener)
      const dispatch = (action) => {
        state = reducer(state, action)
        listeners.forEach((listener) => listener())
      }

      dispatch({})

      return {
        getState,
        dispatch,
        subscribe
      }
    }

    //默认的初始状态
    const countState = {
      count: 0
    }

    //每次返回一个新的状态, redux 里面称为 reducer
    const changeState = (state, action) => {
      if (!state) return countState;
      switch (action.type) {
        case "COUNT_DECREMENT":
          return {
            count: state.count - action.num
          }
        case "COUNT_INCREMENT":
          return {
            count: state.count + action.num
          }
        default:
          return state
      }

    }
    
    
    
    const store = createStore(changeState);
    // 定义一个方法用于渲染计数器的dom
    const render = () => {
      document.getElementById('count').innerHTML = store.getState().count;
    }
     // 首次渲染数据
    render();
    // 监听，只要有dispatch，render就会自动运行
    store.subscribe(render)
  </script>

</body>

</html>